package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"gopkg.in/yaml.v2"
)

type DestConfig struct {
	Network string `json:"network,omitempty" yaml:"network"`
	Addr    string `json:"addr,omitempty" yaml:"addr"`
}

type Config struct {
	Listen string                 `json:"listen,omitempty" yaml:"listen"`
	Path   string                 `json:"path,omitempty" yaml:"path"`
	Dest   DestConfig             `json:"dest,omitempty" yaml:"dest"`
	Aux    map[string]interface{} `json:"aux,omitempty" yaml:"aux"`
}

func loadConfig(path string) (Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return Config{}, err
	}
	defer f.Close() // nolint
	content, err := ioutil.ReadAll(f)
	if err != nil {
		return Config{}, err
	}
	if strings.HasSuffix(path, ".json") {
		var config Config
		err = json.Unmarshal(content, &config)
		return config, err
	} else if strings.HasSuffix(path, ".yml") || strings.HasSuffix(path, ".yaml") {
		var config Config
		err := yaml.Unmarshal(content, &config)
		fmt.Printf("config = %+v\n", config)
		return config, err
	} else {
		return Config{}, fmt.Errorf("unknown config format")
	}
}
